<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="searchDialog"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getList"
        uniqueId="mesUserExtendTable"
      ></ele-page>
    </div>
    <ele-form-drawer class="dialog-pack" :isLoading="isLoading" v-model="formDataDialog" v-bind="formDescDialog" :request-fn="handleSubmit" :visible.sync="visible" :title="title" size="60%">
      <!-- 下方template标签放入ele-form-drawer中, 并且需要自行修改插槽属性及绑定表单对象的属性 -->
      <template v-slot:userCode>
        <!-- 插槽内容有el-form-item组件包裹 -->
        <el-input v-model="formDataDialog.userCode" readonly :placeholder="$t('mesTeam.selectUser')">
          <el-button slot="append" icon="el-icon-search" @click="baseUserDialogVisible = true"></el-button>
        </el-input>
      </template>
    </ele-form-drawer>
    <!-- 此组件放到与抽屉平级，理论上不需要修改 -->
    <ele-dialog-table
      :title="$t('mesTeam.userQuery')"
      width="800px"
      :visible.sync="baseUserDialogVisible"
      :formConfig="baseUserSearchDialog"
      :column="baseUserDialogColumn"
      @getSelectData="getSelectBaseUser"
      :getList="getBaseUserList"
      :hasFooter="hasBaseUserFooter"
    ></ele-dialog-table>
  </div>
</template>

<script>
import { operateList, searchConfig, formDescDialogMixin, rowConfig } from './config'
import {
  getList,
  rowCreate,
  rowUpdate,
  rowDel,
  rowDetail,
  getUserCodeList,
  getLineCodeList,
  getTeamCodeList,
  getWorkCellCodeList,
  getEducationList,
  getSkillsCertificationList,
  getWorkTypeList,
  getEmployeeTypeList,
  getDepartmentList,
  getUserTypeList,
  getPostCodeList,
  getPositionCodeList
} from '@/api/employee/mesUserExtend'
import { popover } from '../../../utils/judge'

import { baseUserDialog } from './mixin'

export default {
  name: 'mesUserExtend',
  mixins: [baseUserDialog, formDescDialogMixin, searchConfig],
  data() {
    const self = this
    return {
      title: null,
      visible: false,
      isLoading: false,
      loading: false,
      skillList: [],
      formDataDialog: {},
      // formDescDialog, //新增修改框
      operateList,
      getList,
      submitProdAreaList: [],
      submitProdLineList: [],
      submitWorkCellList: [],
      submitPostList: [],
      submitPositionList: [],
      submitTeamList: [],
      // 列表页字段的绑定配置
      column: [
        {
          type: 'selection',
          fixed: 'left'
        },
        {
          type: 'index',
          label: $i18n.t('common.order'),
          width: 60,
          fixed: 'left'
        },
        {
          prop: 'userCode',
          label: $i18n.t('mesUserExtend.userCode'),
          minWidth: 120,
          showOverflowTooltip: true
          // optionProp: {
          //   value: 'value',
          //   label: 'description',
          // },
          // option: async (data) => {
          //   const list = await getUserCodeList()
          //   return list.data.result
          // },
        },
        {
          prop: 'userName',
          label: $i18n.t('mesUserExtend.userName'),
          minWidth: 130,
          showOverflowTooltip: true
        },
        {
          prop: 'departmentCode',
          label: '部门名称',
          minWidth: 130,
          optionProp: {
            value: 'value',
            label: 'description',
          },
          showOverflowTooltip: true,
          option: async () => {
            const list = await getDepartmentList()
            return list.data.result
          },
        },
        {
          prop: 'workTypeName',
          label: '工种',
          minWidth: 130,
          showOverflowTooltip: true,
          // optionProp: {
          //   value: 'value',
          //   label: 'description',
          // },
          // option: async () => {
          //   const list = await getWorkTypeList()
          //   return list.data.result
          // }
        },
        {
          prop: 'skillsCertificationName',
          label: '技能认证',
          minWidth: 180,
          showOverflowTooltip: true,
          // optionProp: {
          //   value: 'value',
          //   label: 'description',
          // },
          // option: async () => {
          //   console.log(self)
          //   const list = await getSkillsCertificationList()
          //   self.skillList = list.data.result
          //   return list.data.result.map(ele => { return {value: ele.value, description: ele.description}})
          
          // },
          // render: (h, scope) => {
          //   const list = self.skillList
          //   console.log(self.skillList)
          //   // let skillsCodes = scope.row.skillsCertificationCode.split(',')
          //   // let skillsStr = skillsCodes.map(code => {
          //   //   return list.find(e => { return e.value == code}).description
          //   // }).join(',')
          //   return <span>{skillsStr}</span>
          // },
        },
        {
          prop: 'employeeTypeCode',
          label: '是否为外包人员',
          minWidth: 130,
          showOverflowTooltip: true,
          optionProp: {
            value: 'value',
            label: 'description',
          },
          option: async () => {
            const list = await getEmployeeTypeList()
            return list.data.result
          },
        },
        {
          prop: 'workshopCode',
          label: $i18n.t('common.workshopCode'),
          minWidth: 120,
          showOverflowTooltip: true
        },
        {
          prop: 'workshopName',
          label: $i18n.t('common.workshopName'),
          minWidth: 130,
          showOverflowTooltip: true
        },
        {
          prop: 'lineCode',
          label: $i18n.t('common.lineCode'),
          minWidth: 120,
          showOverflowTooltip: true,
          optionProp: {
            value: 'modelingCode',
            label: 'modelingCode'
          },
          option: async (data) => {
            const params = {
              modelingCode: this.$store.getters.factoryCode,
              level: 5
            }
            const list = await getLineCodeList(params)
            // self.submitProdLineList = list.data.result
            return list.data.result
          }
        },
        {
          prop: 'lineName',
          label: $i18n.t('common.lineName'),
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'workCellCode',
          label: $i18n.t('common.workCellCode'),
          minWidth: 120,
          showOverflowTooltip: true
          // optionProp: {
          //   value: "modelingCode",
          //   label: "modelingCode",
          // },
          // option: async (data) => {
          //
          //   const list = await getWorkCellCodeList()
          //   self.submitWorkCellList = list.data.result
          //   console.log("<<<<<<  "+self.submitWorkCellList.length)
          //   return list.data.result
          // },
        },
        {
          prop: 'workCellName',
          label: $i18n.t('common.workCellName'),
          minWidth: 130,
          showOverflowTooltip: true
        },
        {
          prop: 'teamCode',
          label: '班组编码',
          minWidth: 120,
          showOverflowTooltip: true,
        },
        {
          prop: 'teamCode',
          label: '班组名称',
          minWidth: 120,
          showOverflowTooltip: true,
          optionProp: {
            value: 'teamCode',
            label: 'teamName'
          },
          option: async (data) => {
            const list = await getTeamCodeList()
            return list.data.result
          }
        },

        {
          prop: 'education',
          label: $i18n.t('mesUserExtend.education'),
          showOverflowTooltip: true,
          minWidth: 100,
          optionProp: {
            value: 'value',
            label: 'description'
          },
          option: async (data) => {
            const list = await getEducationList()
            return list.data.result
          }
        },
        {
          prop: 'birthday',
          label: $i18n.t('mesUserExtend.birthday'),
          minWidth: '160',
          showOverflowTooltip: true
        },
        {
          prop: 'timeEntry',
          label: $i18n.t('mesUserExtend.timeEntry'),
          minWidth: '170',
          showOverflowTooltip: true
        },
        {
          prop: 'departureTime',
          label: $i18n.t('mesUserExtend.departureTime'),
          minWidth: '170',
          showOverflowTooltip: true
        },
        {
          prop: 'userType',
          label: $i18n.t('mesUserExtend.userType'),
          minWidth: 120,
          showOverflowTooltip: true,
          optionProp: {
            value: 'value',
            label: 'description'
          },
          option: async (data) => {
            const list = await getUserTypeList()
            return list.data.result
          }
        },
        // {
        //   prop: 'postCode',
        //   label: $i18n.t('common.postCode'),
        //   minWidth: 120,
        //   showOverflowTooltip: true
        //   // optionProp: {
        //   //   value: "value",
        //   //   label: "description",
        //   // },
        //   // option: async (data) => {
        //   //   const list = await getPostCodeList();
        //   //   return list.data.result;
        //   // },
        // },
        // {
        //   prop: 'postName',
        //   label: $i18n.t('common.postName'),
        //   minWidth: 120,
        //   showOverflowTooltip: true
        // },
        {
          prop: 'email',
          label: $i18n.t('mesUserExtend.email'),
          minWidth: 200,
          showOverflowTooltip: true
        },
        {
          prop: 'phone',
          label: $i18n.t('mesUserExtend.phone'),
          minWidth: 160,
          showOverflowTooltip: true
        },
        // {
        //   prop: 'positionCode',
        //   label: $i18n.t('common.positionCode'),
        //   minWidth: 120,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'positionName',
        //   label: $i18n.t('common.positionName'),
        //   minWidth: 120,
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'userFace',
        //   label: $i18n.t('mesUserExtend.userAvatar'),
        //   minWidth: 210,
        //   showOverflowTooltip: true,
        //   render: (h, scope) => {
        //     return popover(scope.row.userFace, h)
        //   }
        // },
        // {
        //   prop: "factoryCode",
        //   label: "工厂编码",
        //   minWidth: 120,
        //   showOverflowTooltip: true,
        // },
        // {
        //   prop: "remark",
        //   label: "备注",
        //   showOverflowTooltip: true,
        // },
        {
          prop: 'createByName',
          label: $i18n.t('common.createByName'),
          width: 130,
          showOverflowTooltip: true
        },
        {
          prop: 'createTime',
          label: $i18n.t('common.createTime'),
          width: 170
        },
        {
          prop: 'updateByName',
          label: $i18n.t('common.updateByName'),
          width: 130,
          showOverflowTooltip: true
        },
        {
          prop: 'updateTime',
          label: $i18n.t('common.updateTime'),
          width: 170
        },
        {
          prop: 'operate',
          label: $i18n.t('common.operation'),
          width: 160,
          fixed: 'right',
          render: (h, scope) => {
            return <ele-row-operation scope={scope} rowConfig={rowConfig} onRowOperate={this.rowOperate} />
          }
        }
      ]
    }
  },
  computed: {},
  methods: {
    // handleSelect(val, field, options) {
    //   console.log(val+","+field+","+options)
    //   if (!val) {
    //     this.formDataDialog[field] = undefined
    //   } else {
    //     const selected = options.find((item) => item.value == val)
    //     this.formDataDialog[field] = selected.modelingName
    //   }
    // },
    // handleChange (val) {
    //   this.formDataDialog.workCellCode = ''
    //   this.formDataDialog.teamCode = ''
    //   this.formDescDialog.formDesc.workCellCode.options = []

    //   if (!val) return
    //   const params = {
    //     modelingCode: val
    //   }
    //   getWorkCellCodeList(params)
    //     .then((res) => {
    //       const { result } = res.data
    //       this.formDescDialog.formDesc.workCellCode.options = result || []
    //       this.submitWorkCellList = result || []
    //     })
    //     .catch((err) => {
    //       console.log('----==', err)
    //     })
    // },
    handleSearchChange(val) {
      if (!val) return
      const params = {
        modelingCode: val
      }
      this.formDescDialog.formDesc.workCellCode.options = []
      getWorkCellCodeList(params)
        .then((res) => {
          const { result } = res.data
          this.searchDialog.formDesc.workCellCode.options = result || []
        })
        .catch((err) => {
          console.log('----==', err)
        })
    },
    // 表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name
      const fnc = {
        add: () => {
          this.disableFields(false)
          this.formDataDialog = {
          }
          this.visible = true
        },
        deleteBatch: () => {
          this.$confirm($i18n.t('common.deleteBatch', { name: $i18n.t('mesUserExtend.name') }), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            const ids = data.rows.map((val) => val.id).join(',')
            this.rowDel(ids)
          })
        },
        // 导入
        uploadFile: () => {}
      }
      fnc[data.handleName]()
    },
    // 表格行操作事件
    rowOperate({ handleName, name, row }) {
      this.title = name
      const fnc = {
        edit: () => {
          this.disableFields(false)
          this.rowDetail(row.id)
          this.visible = true
        },
        detail: () => {
          this.disableFields(true)
          this.rowDetail(row.id)
          this.visible = true
        },
        delete: () => {
          this.$confirm($i18n.t('common.deleteSingle', { name: $i18n.t('mesUserExtend.name') }), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.rowDel(row.id)
          })
        }
      }
      fnc[handleName]()
    },
    doSubmit({ title, api, data }) {
      this.isLoading = true
      api(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || title)
          this.visible = false
          this.refresh()
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return // 判断状态 submitProdAreaList
      // 车间信息
      const areaItem = this.submitProdAreaList.find((val) => val.modelingCode == data.workshopCode)

      // 配对车间、线体、工位信息
      if (areaItem != undefined) {
        data.workshopName = areaItem.modelingName
        // 线体信息
        const item = this.submitProdLineList.find((val) => val.modelingCode == data.lineCode)
        if (item != undefined) {
          data.lineName = item.modelingName
          const itemWorkc = this.submitWorkCellList.find((val) => val.modelingCode == data.workCellCode)
          // 工位信息
          if (itemWorkc != undefined) {
            data.workCellName = itemWorkc.modelingName
          } else {
            data.workCellName = ''
            data.workCellCode = ''
          }
          // 班组信息
          const itemTeam = this.submitTeamList.find((val) => val.teamCode == data.teamCode)
          if (itemTeam != undefined) {
            data.teamName = itemTeam.teamName
          } else {
            data.teamName = ''
            data.teamCode = ''
          }
        } else {
          data.lineName = ''
          data.lineCode = ''
          data.workCellName = ''
          data.workCellCode = ''
          data.teamName = ''
          data.teamCode = ''
        }
      } else {
        data.workshopName = ''
        data.workshopCode = ''
        data.lineName = ''
        data.lineCode = ''
        data.workCellName = ''
        data.workCellCode = ''
        data.teamName = ''
        data.teamCode = ''
      }

      if (data.userFace) {
        data.userFace = data.userFace.map((r) => r.src).join(',')
      }
      if(data.skillsCertificationCode) {
        data.skillsCertificationCode = data.skillsCertificationCode.join(',')
      }
      if(data.workTypeCode) {
        data.workTypeCode = data.workTypeCode.join(',')
      }
      const params = this.formDataDialog.id
        ? {
            title: $i18n.t('common.editSuccess'),
            api: rowUpdate,
            data
          }
        : {
            title: $i18n.t('common.addSuccess'),
            api: rowCreate,
            data
          }
      console.log(params)
      this.doSubmit(params)
    },
    // 删除
    rowDel(data) {
      this.loading = true
      rowDel(data)
        .then((res) => {
          const message = res.data.message
          this.$message.success(message || $i18n.t('common.deleteSuccess'))
          this.refresh()
        })
        .finally(() => {
          this.loading = false
        })
    },
    disableFields(flag) {
      this.formDescDialog.disabled = flag
      this.formDescDialog.isShowSubmitBtn = !flag
    },
    rowDetail(id) {
      rowDetail(id).then((res) => {
        const { userFace } = res.data.result
        // console.log("<<<>>>>>>> ",res.data.result)
        // this.formDataDialog.formDesc.workCellCode.options = result || []
        const userFaces = userFace
          ? userFace.split(',').map((val) => {
              const arr = val.split('/')
              return {
                src: val,
                title: arr[arr.length - 1]
              }
            })
          : []
        this.formDataDialog = {
          ...res.data.result,
          userFace: userFaces,
          skillsCertificationCode: res.data.result.skillsCertificationCode.split(','),
          workTypeCode: res.data.result.workTypeCode.split(','),
        }
      })
    },
    // 刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset)
    }
  }
}
</script>
